package com.mango.request;

import android.support.annotation.Nullable;
import android.text.Html;

import com.mango.config.DeviceConfig;
import com.mango.config.NetworkConfig;
import com.mango.request.beans.AdvertBean;
import com.mango.request.beans.AdvertBean.*;
import com.mango.volley.Response;
import com.mango.wall.BuildConfig;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ReqMgAdList extends ReqMango<Map<Integer, List<AdvertBean>>> {
    private final String mAppID, mUserID;
    private final int mAdNum, mAdType, mAdPosId;

    public ReqMgAdList(String appID, String appKey, int adNum, int adType, int adPosId, String userID,
                       @Nullable Response.Listener<Map<Integer, List<AdvertBean>>> listener,
                       @Nullable Response.ErrorListener errorListener) {
        super("api/ad/list", new Object[]{"appId", appID, null, appKey,
                "timeStamp", System.currentTimeMillis()}, listener, errorListener);
        mAppID = appID;
        mAdNum = adNum;
        mAdType = adType;
        mUserID = userID;
        mAdPosId = adPosId;
    }

    @Override
    protected String getJsonParams() throws JSONException {
        JSONObject root = new JSONObject()
                .put("sdkVersion", BuildConfig.VERSION)
                .put("protocolVersion", "1.0")
                .put("adType", mAdType);

        root.put("appInfo", DeviceConfig.getPackage(mAppID));

        root.put("impInfo", new JSONArray().put(new JSONObject()
                .put("adNum", mAdNum)
                .put("posId", mAdPosId)
                .put("width", 1280)
                .put("height", 1920)
                .put("bidPrice", null)));

        root.put("deviceInfo", new JSONObject()
                .put("imei", DeviceConfig.getImei())
                .put("oaid", DeviceConfig.getOaid())
                .put("imeiMd5", DeviceConfig.getImeiMd5())
                .put("osType", 1)
                .put("osv", DeviceConfig.getOsv())
                .put("osc", DeviceConfig.getOsc())
                .put("screenType", DeviceConfig.getScreenType())
                .put("dpi", DeviceConfig.getDpi())
                .put("dip", DeviceConfig.getDip())
                .put("serialno", DeviceConfig.getSerialno())
                .put("manufacture", DeviceConfig.getManufacture())
                .put("model", DeviceConfig.getModel())
                .put("brand", DeviceConfig.getBrand())
                .put("deviceType", DeviceConfig.getDeviceType())
                .put("screenSize", DeviceConfig.getScreenSize())
                .put("imsi", DeviceConfig.getImsi())
                .put("language", DeviceConfig.getLanguage())
                .put("screenWidth", DeviceConfig.getScreenWidth())
                .put("screenHeight", DeviceConfig.getScreenHeight())
                .put("androidId", DeviceConfig.getAndroidId())
                .put("androidIdMd5", DeviceConfig.getAndroidIdMd5())
                .put("incremental", DeviceConfig.getIncremental())
                .put("iccid", DeviceConfig.getIccid())
                .put("screenBrightness", DeviceConfig.getScreenBrightness())
                .put("angle", DeviceConfig.getAngle())
                .put("hardware", DeviceConfig.getHardware())
                .put("battery", DeviceConfig.getBattery())
                .put("appStoreVersion", DeviceConfig.getAppStoreVersion())
                .put("romVersion", DeviceConfig.getRomVersion())
                .put("bootMark", DeviceConfig.getBootMark())
                .put("updateMark", DeviceConfig.getUpdateMark())
                .put("appPackageName", DeviceConfig.getInstallations()));

        root.put("networkInfo", new JSONObject()
                .put("ip", NetworkConfig.getIp())
                .put("ip6", NetworkConfig.getIp6())
                .put("mac", NetworkConfig.getMac())
                .put("macMd5", NetworkConfig.getMacMd5())
                .put("connectionType", NetworkConfig.getConnectionType())
                .put("operatorType", NetworkConfig.getOperatorType())
                .put("mno", NetworkConfig.getMno())
                .put("bssid", NetworkConfig.getBssid())
                .put("ssid", NetworkConfig.getSsid())
                .put("infoLA", NetworkConfig.getInfoLA())
                .put("infoCI", NetworkConfig.getInfoCI())
                .put("userAgent", NetworkConfig.getUserAgent()));

//        root.put("geoInfo", new JSONObject()
//                .put("coordinateType", 0)
//                .put("latitude", "")
//                .put("longitude", "")
//                .put("address", ""));

        root.put("userInfo", new JSONObject()
                .put("userId", mUserID)
                /*.put("mobile", 0)
                .put("age", 0)
                .put("gender", "")
                .put("interest", "")*/);

        return root.toString();
    }

    @Override
    protected Map<Integer, List<AdvertBean>> parseJsonResult(String json) throws JSONException {
        JSONArray data = new JSONObject(json).getJSONArray("data");
        Map<Integer, List<AdvertBean>> result = new HashMap<>();

        final int size = data.length();
        for (int i = 0; i < size; i++) {
            JSONObject item = data.optJSONObject(i);
            if (item == null) continue;

            JSONArray adInfo = item.optJSONArray("adInfo");
            if (adInfo == null) continue;

            List<AdvertBean> adverts = new ArrayList<>();
            result.put(item.optInt("posId"), adverts);

            final int adSize = adInfo.length();
            for (int j = 0; j < adSize; j++) {
                JSONObject itemInfo = adInfo.optJSONObject(j);
                if (itemInfo == null) continue;

                JSONObject baseInfo = itemInfo.optJSONObject("adBaseInfo");
                JSONObject materialInfo = itemInfo.optJSONObject("adMaterialInfo");
                JSONObject conversionInfo = itemInfo.optJSONObject("adConversionInfo");
                if (baseInfo == null || materialInfo == null || conversionInfo == null) continue;

                AdvertBean adBean = new AdvertBean();
                adverts.add(adBean);

                adBean.adBaseInfo = new AdBaseBean();
                adBean.adMaterialInfo = new AdMaterialBean();
                adBean.adConversionInfo = new AdConversionBean();

                adBean.adBaseInfo.adid = baseInfo.optInt("adid");
                adBean.adBaseInfo.creativeId = baseInfo.optInt("creativeId");
                adBean.adBaseInfo.adTitle = baseInfo.optString("adTitle");
                adBean.adBaseInfo.adDescription = Html.fromHtml(baseInfo.optString("adDescription")).toString();
                adBean.adBaseInfo.adOperationType = baseInfo.optInt("adOperationType");
                adBean.adBaseInfo.adShowDuration = baseInfo.optInt("adShowDuration");
                adBean.adBaseInfo.adActionDescription = baseInfo.optString("adActionDescription");
                adBean.adBaseInfo.appName = baseInfo.optString("appName");
                adBean.adBaseInfo.appIconUrl = baseInfo.optString("appIconUrl");
                adBean.adBaseInfo.appPackageName = baseInfo.optString("appPackageName");
                adBean.adBaseInfo.appScore = baseInfo.optInt("appScore");
                adBean.adBaseInfo.appSize = baseInfo.optInt("appSize");
                adBean.adBaseInfo.expirationTime = baseInfo.optInt("expirationTime");
                adBean.adBaseInfo.integral = baseInfo.optInt("integral");
                adBean.adBaseInfo.biddingType = baseInfo.optInt("biddingType");
                adBean.adBaseInfo.price = baseInfo.optInt("price");

                adBean.adBaseInfo.convUrl = new HashMap<>();
                JSONObject convUrl = baseInfo.optJSONObject("convUrl");
                if (convUrl != null) {
                    Iterator<String> it = convUrl.keys();
                    while (it.hasNext()) {
                        String key = it.next();

                        ActionType type = ActionType.getType(key);
                        if (type == ActionType.UNKNOWN) continue;

                        JSONArray values = convUrl.optJSONArray(key);
                        if (values == null) continue;

                        final int urlSize = values.length();
                        String[] urls = new String[urlSize];
                        for (int k = 0; k < urlSize; k++) {
                            urls[k] = values.optString(k);
                        }
                        adBean.adBaseInfo.convUrl.put(type, urls);
                    }
                }

                adBean.adMaterialInfo.materialFeature = new ArrayList<>();
                adBean.adMaterialInfo.materialType = materialInfo.optInt("materialType");

                JSONArray feature = materialInfo.optJSONArray("materialFeature");
                if (feature != null) {
                    final int featureSize = feature.length();
                    for (int k = 0; k < featureSize; k++) {
                        JSONObject featureItem = feature.optJSONObject(k);
                        if (featureItem == null) continue;

                        AdMaterialFeatureBean featureBean = new AdMaterialFeatureBean();
                        adBean.adMaterialInfo.materialFeature.add(featureBean);

                        featureBean.clickable = featureItem.optInt("clickable");
                        featureBean.featureType = featureItem.optInt("featureType");
                        featureBean.materialUrl = featureItem.optString("materialUrl");
                        featureBean.coverUrl = featureItem.optString("coverUrl");
                        featureBean.coverType = featureItem.optInt("coverType");
                        featureBean.videoDuration = featureItem.optInt("videoDuration");
                        featureBean.countdownType = featureItem.optInt("countdownType");
                        featureBean.videoDPType = featureItem.optInt("videoDPType");
                        featureBean.videoSecond = featureItem.optInt("videoSecond");
                        featureBean.videoStyle = featureItem.optInt("videoStyle");

                        JSONObject materialSize = featureItem.optJSONObject("materialSize");
                        featureBean.materialSize = new AdMaterialSizeBean();
                        if (materialSize != null) {
                            featureBean.materialSize.width = materialSize.optInt("width");
                            featureBean.materialSize.height = materialSize.optInt("height");
                        }
                    }
                }

                adBean.adConversionInfo.h5Url = conversionInfo.optString("h5Url");
                adBean.adConversionInfo.deeplinkUrl = conversionInfo.optString("deeplinkUrl");
                adBean.adConversionInfo.appDownloadUrl = conversionInfo.optString("appDownloadUrl");
            }
        }

        return result;
    }
}
